import React, { useState, useEffect } from 'react';
import ChatMessage from './components/ChatMessage';
import { View, StyleSheet, TouchableOpacity, TextInput, FlatList, Image, Text, ScrollView } from 'react-native';
import FriendItem from './components/FriendItem';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useNavigation } from '@react-navigation/native';
import { initSocket } from '../../services/socket';
import { MessageStorage, Friend } from '../../services/messageStorage';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../../navigation/types';
import { useSelector } from 'react-redux';
import FriendRequestItem, { FriendRequest } from './components/FriendRequestItem';
import api from '../../api';
const MessageScreen = () => {
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('chats');
  const [friendRequests, setFriendRequests] = useState<FriendRequest[]>([]);
  const [socket, setSocket] = useState<WebSocket | null>(null);
  const [friends, setFriends] = useState<Friend[]>([]);
  const [recentChats, setRecentChats] = useState<{[key: string]: Friend & {lastMessage?: any}}>({});
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const userInfo = useSelector((state: any) => state.auth.userInfo);

  // 初始化WebSocket连接
  useEffect(() => {
    if (userInfo?._id) {
      const ws = initSocket(userInfo._id);
      setSocket(ws);

      // 组件卸载时关闭连接
      return () => {
        if (ws ) {
          ws.close();
        }
      };
    }
  }, [userInfo?._id]);
  useEffect(() => {
    // 获取本地存储的好友请求
    const loadFriendRequests = async () => {
      try {
        const requests = await MessageStorage.getFriendRequests();
        // 过滤出与当前用户相关的请求，并确保数据格式完整
        const userRequests = requests
          .filter(request => 
            request.receiverId === userInfo?._id || request.senderId === userInfo?._id
          )
          .map(request => ({
            ...request,
            content: request.content || '新的好友请求',  // 确保有content字段
            status: request.status || 'pending',  // 确保有status字段
            timestamp: request.timestamp || Date.now()  // 确保有timestamp字段
          }));
        
        // 按时间戳降序排序
        const sortedRequests = userRequests.sort((a, b) => b.timestamp - a.timestamp);
        setFriendRequests(sortedRequests)
      } catch (error) {
        console.error('加载好友请求失败:', error);
      }
    };

    // 获取本地存储的好友列表和最近聊天记录
    const loadFriends = async () => {
      try {
        const friends = await api.get('/zt/friends?_id='+userInfo?._id);
        const friendsList = friends.data.data;
        setFriends(friendsList);
    
        // 加载每个好友的最新消息
        const recentChatsMap: {[key: string]: Friend & {lastMessage?: any}} = {};
        for (const friend of friendsList) {
          const messages = await MessageStorage.getMessages(userInfo?._id || '', friend._id);
          if (messages.length > 0) {
            const lastMessage = messages[messages.length - 1];
            recentChatsMap[friend._id] = {
              ...friend,
              lastMessage: {
                id: lastMessage.id,
                content: lastMessage.content,
                timestamp: lastMessage.timestamp,
                status: lastMessage.status
              }
            };
          }
        }
        setRecentChats(recentChatsMap);
      } catch (error) {
        console.error('加载好友列表和聊天记录失败:', error);
      }
    };
    loadFriends();
    // 监听WebSocket消息
    if (socket) {
      socket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        console.log('Received message:', message);
        // 根据消息类型进行处理
        switch (message.type) {
          case 'friendRequest':
            // 更新好友请求列表
            setFriendRequests(prevRequests => [
              ...prevRequests,
              {
                ...message,
                content: message.content || '新的好友请求',
                status: message.status || 'pending',
                timestamp: message.timestamp || Date.now()
              }
            ]);
            break;
          
          case 'friendRequestUpdate':
            // 更新好友请求状态
            setFriendRequests(prevRequests =>
              prevRequests.map(request =>
                request.requestId === message.id
                  ? { ...request, status: message.status }
                  : request
              )
            );
            // 如果请求被接受，刷新好友列表
            if (message.status === 'accepted') {
              loadFriends();
            }
            break;

          case 'chat':
            // 更新最近聊天列表
            const chatPartnerId = message.senderId === userInfo._id ? message.receiverId : message.senderId;
            const chatPartner = friends.find(f => f._id === chatPartnerId);
            
            if (chatPartner) {
              setRecentChats(prevChats => ({
                ...prevChats,
                [chatPartnerId]: {
                  ...chatPartner,
                  lastMessage: {
                    id: message.id,
                    content: message.content,
                    timestamp: message.timestamp || Date.now(),
                    status: 'delivered'
                  }
                }
              }));
            }
            break;

          default:
            console.log('未处理的消息类型:', message.type);
        }
      };
    }
    if (userInfo?._id) {
      loadFriendRequests();
    }
  }, [userInfo?._id]);

  const handleStatusChange = async (requestId: string, newStatus: 'accepted' | 'rejected') => {
    try {
      // 更新本地状态
      const updatedRequests = friendRequests.map(request =>
        request.requestId === requestId ? { ...request, status: newStatus } : request
      );
      setFriendRequests(updatedRequests);

      // 找到对应的请求
      const request = friendRequests.find(r => r.requestId === requestId);
      if (request) {
        // 更新本地存储
        await MessageStorage.updateFriendRequest({
          ...request,
          status: newStatus,
          timestamp: Date.now(),
          requestId: requestId

        });

        // 通过WebSocket发送状态更新
        if (socket ) {
          socket.send(JSON.stringify({
            type: 'friendRequestUpdate',
            id: requestId,
            senderId: request.senderId,
            receiverId: request.receiverId,
            status: newStatus,
            timestamp: Date.now()
          }));
        }

        // 如果是接受好友请求，调用后端API更新好友关系
        if (newStatus === 'accepted') {
          try {
            const response = await api.put(`/zt/friend-requests/${requestId}`, {
              status: newStatus,
              senderId: request.senderId,
              receiverId: request.receiverId
            });

            if (!response) {
              throw new Error('更新好友关系失败');
            }

            console.log('好友关系已更新');
          } catch (error) {
            console.error('调用后端API失败:', error);
            // 可以考虑在这里添加错误处理UI提示
          }
        }
      }
    } catch (error) {
      console.error('更新好友请求状态失败:', error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.searchContainer}>
        <MaterialIcons name="search" size={20} color="#666" style={styles.searchIcon} />
        <TextInput
          style={styles.searchInput}
          placeholder="添加好友"
          placeholderTextColor="#888"
          value={searchText}
          onChangeText={setSearchText}
          onSubmitEditing={() => {
            navigation.navigate('ZTsearch', { searchText });
          }}
        />
        {searchText ? (
          <TouchableOpacity onPress={() => setSearchText('')}>
            <MaterialIcons name="close" size={20} color="#666" />
          </TouchableOpacity>
        ) : null}
      </View>

      <View style={styles.tabBar}>
        <TouchableOpacity 
          style={[styles.tabItem, activeTab === 'chats' && styles.activeTab]}
          onPress={() => setActiveTab('chats')}
        >
          <Text style={[styles.tabText, activeTab === 'chats' && styles.activeTabText]}>聊天</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          style={[styles.tabItem, activeTab === 'friends' && styles.activeTab]}
          onPress={() => setActiveTab('friends')}
        >
          <Text style={[styles.tabText, activeTab === 'friends' && styles.activeTabText]}>好友列表</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          style={[styles.tabItem, activeTab === 'requests' && styles.activeTab]}
          onPress={() => setActiveTab('requests')}
        >
          <Text style={[styles.tabText, activeTab === 'requests' && styles.activeTabText]}>好友请求</Text>
        </TouchableOpacity>
      </View>

      {activeTab === 'chats' && (
        <View style={styles.contentContainer}>
          {Object.keys(recentChats).length > 0 ? (
            <FlatList
              data={Object.values(recentChats)}
              keyExtractor={item => item._id}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={styles.chatItem}
                  onPress={() => {
                    navigation.navigate('Chat', {
                      friendId: item._id,
                      friendName: item.username
                    });
                  }}
                >
                  <Image
                    source={{ uri: item.avatar || 'https://via.placeholder.com/50' }}
                    style={styles.avatar}
                  />
                  <View style={styles.chatInfo}>
                    <Text style={styles.username}>{item.username}</Text>
                    {item.lastMessage && (
                      <Text style={styles.lastMessage} numberOfLines={1}>
                        {item.lastMessage.content}
                      </Text>
                    )}
                  </View>
                  {item.lastMessage && (
                    <Text style={styles.messageTime}>
                      {new Date(item.lastMessage.timestamp).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </Text>
                  )}
                </TouchableOpacity>
              )}
            />
          ) : (
            <Text style={styles.emptyText}>暂无聊天记录</Text>
          )}
        </View>
      )}

      {activeTab === 'friends' && (
        <View style={styles.contentContainer}>
          {friends.length > 0 ? (
            <ScrollView style={styles.friendList}>
              {friends.map(friend => (
                <FriendItem
                  key={friend._id}
                  friend={friend}
                  onPress={(friend) => {
                    navigation.navigate('Chat', {
                      friendId: friend._id,
                      friendName: friend.username
                    });
                  }}
                />
              ))}
            </ScrollView>
          ) : (
            <Text style={styles.emptyText}>暂无好友</Text>
          )}
        </View>
      )}

      {activeTab === 'requests' && friendRequests.length > 0 && (
        <View style={styles.requestsSection}>
          <ScrollView style={styles.requestList}>
            {friendRequests.map(request => (
              <FriendRequestItem
                key={request.timestamp}
                request={request}
                currentUserId={userInfo?._id}
                onStatusChange={handleStatusChange}
              />
            ))}
          </ScrollView>
        </View>
      )}

      {activeTab === 'requests' && friendRequests.length === 0 && (
        <View style={styles.contentContainer}>
          <Text style={styles.emptyText}>暂无好友请求</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderWidth: 0,
    marginHorizontal: 16,
    marginTop: 12,
    marginBottom: 8,
    backgroundColor: '#f0f0f0',
    height: 40,
    borderRadius: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
  },
  searchIcon: {
    marginRight: 8,
    color: '#666',
    width: 20,
    height: 20,
  },
  searchInput: {
    flex: 1,
    fontSize: 15,
    color: '#333',
    height: 40,
    paddingVertical: 0,
    includeFontPadding: false,
    textAlignVertical: 'center',
  },
  tabBar: {
    flexDirection: 'row',
    marginHorizontal: 16,
    marginTop: 8,
    marginBottom: 16,
    backgroundColor: '#f8f8f8',
    borderRadius: 8,
    padding: 4,
  },
  tabItem: {
    flex: 1,
    paddingVertical: 8,
    alignItems: 'center',
    borderRadius: 6,
  },
  activeTab: {
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  tabText: {
    fontSize: 14,
    color: '#666',
  },
  activeTabText: {
    color: '#333',
    fontWeight: 'bold',
  },
  contentContainer: {
    flex: 1,
    width: '100%',
  },
  emptyText: {
    fontSize: 16,
    color: '#999',
    textAlign: 'center',
    marginTop: 20,
  },
  requestsSection: {
    flex: 1,
    marginTop: 8,
  },
  requestList: {
    flex: 1,
  },
  friendList: {
    flex: 1,
    width: '100%',
  },
  chatItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 12,
  },
  chatInfo: {
    flex: 1,
    justifyContent: 'center',
  },
  username: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 4,
  },
  lastMessage: {
    fontSize: 14,
    color: '#666',
  },
  messageTime: {
    fontSize: 12,
    color: '#999',
    marginLeft: 8,
  },
});

export default MessageScreen;